package com.jinlejia.feedback.idea.ui;


import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.FbApiConfig;
import com.jinlejia.feedback.common.FbDataFilter;
import com.jinlejia.feedback.common.RecycleViewDivider;
import com.jinlejia.feedback.databinding.FbFragmentIdeaMineBinding;
import com.jinlejia.feedback.idea.ui.adapter.FbFeedbackAdapter;
import com.jinlejia.feedback.idea.ui.adapter.FBListMapDropDownAdapter;
import com.jinlejia.feedback.idea.ui.bean.FbQuestionListBean;
import com.jinlejia.feedback.question.ui.FbQuestionDetailsActivity;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * 我的
 */
public class FbIdeaMineFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {
    private FbFragmentIdeaMineBinding binding;
    //下拉列表标题
    private String headers[] = {"处理状态", "是否评价"};
    private FBListMapDropDownAdapter arocessingstatusAdapter;    //处理状态
    private FBListMapDropDownAdapter evaluateAdapter;    //是否评价
    //下拉列表集合
    private List<View> popupViews = new ArrayList<>();
    //处理状态数据集合
    private ArrayList<Map<String, Object>> arocessingstatuslist = new ArrayList<>();
    //是否评价
    private ArrayList<Map<String, Object>> evaluatelist = new ArrayList<>();
    //提问列表适配器
    FbFeedbackAdapter fbFeedbackAdapter = new FbFeedbackAdapter(new ArrayList<Map<String, Object>>());

    JSONObject jsonObject = new JSONObject();

    private String state = null;
    private String isEvaluate = null;

    private int pageIndex; //查询第几页

    public FbIdeaMineFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fb_fragment_idea_mine, container, false);
        binding = DataBindingUtil.bind(view);
        binding.setEvent(this);
        binding.yfListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.yfListRecyclerView.setHasFixedSize(true);
        binding.yfListRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.VERTICAL, 20, Color.parseColor("#F4F4F4")));
        binding.swipeRefreshLayout.setOnRefreshListener(this);
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.yfListRecyclerView.setAdapter(fbFeedbackAdapter);
        fbFeedbackAdapter.changeMode(YfListMode.MODE_LOADING);
        fbFeedbackAdapter.setEventitem(new FbFeedbackAdapter.Eventitem() {
            @Override
            public void itemClick(String problemCode) {
                Intent intent = new Intent(getContext(), FbQuestionDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("problemCode",problemCode);
                intent.putExtras(bundle);
                getContext().startActivity(intent);
            }
        });
        initview();
        return view;
    }

    private void initview() {
//处理状态模拟数据
        HashMap<String,Object> hashMap1 = new HashMap<>();
        hashMap1.put("valueName","未受理");
        HashMap<String,Object> hashMap2 = new HashMap<>();
        hashMap2.put("valueName","已受理");
        HashMap<String,Object> hashMap3 = new HashMap<>();
        hashMap3.put("valueName","解决中");
        HashMap<String,Object> hashMap4 = new HashMap<>();
        hashMap4.put("valueName","已完成");
        HashMap<String,Object> hashMap5 = new HashMap<>();
        hashMap5.put("valueName","已解决");
        arocessingstatuslist.add(hashMap1);
        arocessingstatuslist.add(hashMap2);
        arocessingstatuslist.add(hashMap3);
        arocessingstatuslist.add(hashMap4);
        arocessingstatuslist.add(hashMap5);



        final ListView listchuli = new ListView(getContext());
        arocessingstatusAdapter = new FBListMapDropDownAdapter(getContext(),arocessingstatuslist,1);
        arocessingstatusAdapter.setData(arocessingstatuslist);
        listchuli.setDivider(this.getResources().getDrawable(R.drawable.shape_h_line));
        listchuli.setAdapter(arocessingstatusAdapter);
        listchuli.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                arocessingstatusAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[0] : arocessingstatuslist.get(position).get("valueName").toString());
                binding.dropDownMenu.closeMenu();

                if (position==0){
                    state = null;
                    jsonObject.remove("state");
                    pageIndex = 1;
                    getQuestionList(null,state,20,pageIndex,isEvaluate);
                }else if(position == 1 ){
                    state="0";
                    pageIndex = 1;
                    getQuestionList(null,state,20,pageIndex,isEvaluate);
                }else if (position==2){
                    state="1";
                    pageIndex = 1;
                    getQuestionList(null,state,20,pageIndex,isEvaluate);

                }else if (position==3){
                    state="2";
                    pageIndex = 1;
                    getQuestionList(null,state,20,pageIndex,isEvaluate);

                }else if (position==4){
                    state="3";
                    pageIndex = 1;
                    getQuestionList(null,state,20,pageIndex,isEvaluate);

                }else if (position==5){
                    state="4";
                    pageIndex = 1;
                    getQuestionList(null,state,20,pageIndex,isEvaluate);
                }
            }
        });





        //是否评价
        HashMap<String,Object> hashMap6 = new HashMap<>();
        hashMap6.put("valueName","未评价");
        HashMap<String,Object> hashMap7 = new HashMap<>();
        hashMap7.put("valueName","已评价");
        evaluatelist.add(hashMap6);
        evaluatelist.add(hashMap7);




        final ListView evaluatelistview = new ListView(getContext());
        evaluateAdapter = new FBListMapDropDownAdapter(getContext(),evaluatelist,2);
        evaluateAdapter.setData(evaluatelist);
        evaluatelistview.setDivider(this.getResources().getDrawable(R.drawable.shape_h_line));
        evaluatelistview.setAdapter(evaluateAdapter);
        evaluatelistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                evaluateAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[1] : evaluatelist.get(position).get("valueName").toString());
                binding.dropDownMenu.closeMenu();

                if( position==0 ){
                    isEvaluate = null;
                    jsonObject.remove("isEvaluate");
                    pageIndex = 1;
                        getQuestionList(null,state,20,pageIndex,isEvaluate);
                }else if(position == 1){
                    isEvaluate = "0";
                    pageIndex = 1;
                        getQuestionList(null,state,20,pageIndex,isEvaluate);
                }else if (position==2){
                    isEvaluate = "1";
                    pageIndex = 1;
                        getQuestionList(null,state,20,pageIndex,isEvaluate);
                }
            }
        });


        popupViews.add(listchuli);
        popupViews.add(evaluatelistview);
        TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
    }









    /**
     * 网络请求问题列表数据
     * */
    public void getQuestionList(String keyWord, String state, int pageSize, final int pageIndex, String isEvaluate){
        if (!TextUtils.isEmpty(state)){
            jsonObject.put("state",Integer.parseInt(state));
        }
        if (!TextUtils.isEmpty(isEvaluate)){
            jsonObject.put("isEvaluate",Integer.parseInt(isEvaluate));
        }

        if (!TextUtils.isEmpty(keyWord)){
            jsonObject.put("keyWord",keyWord);
        }

        jsonObject.put("pageSize",pageSize);
        jsonObject.put("pageIndex",pageIndex);
        jsonObject.put("type",2);

        OkHttpUtils.postString()
                .url(FbApiConfig.GetQuestionList)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(getContext(),"网络错误"+e.toString(),1500);
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        ArrayList<Map<String, Object>> data = new ArrayList<>();
                        int code = FbDataFilter.code(response);

                        if (code==700){
                            fbFeedbackAdapter.changeMode(YfListMode.MODE_ERROR);
                            return;
                        }
                        if (code == 200 && !showEmptyMessage(response)){
                            JSONArray dataList = (JSONArray) response.get("data");
                            List<FbQuestionListBean> questionListBeans = JSON.parseArray(dataList.toString(),FbQuestionListBean.class);
                            for (FbQuestionListBean questionListBean: questionListBeans) {
                                HashMap<String,Object> map = new HashMap<>();
                                map.put("problemCode",questionListBean.getProblemCode());
                                map.put("problemTitle",questionListBean.getProblemTitle());
                                map.put("askTime",questionListBean.getAskTime());
                                map.put("isGeneral",questionListBean.getIsGeneral());
                                map.put("state",questionListBean.getState());
                                data.add(map);
                            }
                            if (pageIndex==1){
                                fbFeedbackAdapter.setData(data);
                            }else {
                                fbFeedbackAdapter.addData(data);
                            }
                        }else{
                            binding.yfListRecyclerView.enableAutoLoadMore(null);
                            if (pageIndex==1){
                                fbFeedbackAdapter.setData(data);
                            }else {
                                fbFeedbackAdapter.addData(data);
                            }
                        }

                        fbFeedbackAdapter.notifyDataSetChanged();
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private boolean showEmptyMessage(Map<String, Object> response){
        if ("501".equals(String.valueOf(response.get("code")))){
            if (response.get("message") != null)
            return true;
        }
        return false;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 105) {
            String name = data.getStringExtra("data");
            pageIndex = 1;
            getQuestionList(name,state,20,pageIndex,isEvaluate);
        }else if(resultCode == RESULT_CANCELED && requestCode == 105){
            jsonObject.remove("keyWord");
            pageIndex = 1;
            getQuestionList(null,state,20,pageIndex,isEvaluate);
        }
    }


    @Override
    public void onRefresh() {
        pageIndex = 1;
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.swipeRefreshLayout.setRefreshing(true);
        getQuestionList(null,state,20,pageIndex,isEvaluate);
    }

    @Override
    public void loadMore() {
        pageIndex = pageIndex + 1;
        getQuestionList(null,state,20,pageIndex,isEvaluate);
    }


    @Override
    public void onStart() {
        super.onStart();
        pageIndex = 1;
        getQuestionList(null,state,20,1,isEvaluate);
    }
}
